from collections import OrderedDict

from goods.models import GoodsChannel


def get_categories():
    #1，定义所用分类字典
    categories = OrderedDict()
    #2，获取一级分类(37条数据分为11组)
    channels = GoodsChannel.objects.order_by('group_id', 'sequence')

    #3，对一级分类进行遍历
    for channel in channels:
        # 获取group_id
        group_id = channel.group_id
        # 判断group_id 是否在存储容器,如果不在就初始化
        if group_id not in categories:
            categories[group_id] = {
                'channels': [],
                'sub_cats': []
            }
        # 3,1取出一级分类
        one = channel.category
        # 为channels填充数据
        categories[group_id]['channels'].append({
            'id': one.id,
            'name': one.name,
            'url': channel.url
        })
        # 3,2添加二级分类
        # 为sub_cats填充数据
        for two in one.goodscategory_set.all():
            # 初始化 容器
            two.sub_cats = []
            # 3,3遍历获取三级分类
            for three in two.goodscategory_set.all():
                two.sub_cats.append(three)

            # 组织数据
            categories[group_id]['sub_cats'].append(two)
    #4，返回分类信息
            return categories
